package com.monolithiot.notifier.service.impl;

import com.monolithiot.notifier.common.entity.SentSms;
import com.monolithiot.notifier.common.util.DateUtil;
import com.monolithiot.notifier.common.vo.VerifySms;
import com.monolithiot.notifier.dao.BaseMapper;
import com.monolithiot.notifier.dao.mapper.SentSmsMapper;
import com.monolithiot.notifier.service.SentSmsService;
import com.monolithiot.notifier.sms.SmsSender;
import com.monolithiot.notifier.sms.impl.YunPianSmsSenderAdapter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * 2018/12/29 Create by 郭文梁
 * SentSmsServiceImpl
 * 发送短信记录业务行为实现
 *
 * @author 郭文梁
 * @date 2018/12/29
 */
@Slf4j
@Service
public class SentSmsServiceImpl extends BaseServiceImpl<SentSms> implements SentSmsService {
    private final SentSmsMapper sentSmsMapper;
    private final YunPianSmsSenderAdapter yunPianSmsSenderAdapter;

    @Autowired
    public SentSmsServiceImpl(SentSmsMapper sentSmsMapper, YunPianSmsSenderAdapter yunPianSmsSenderAdapter) {
        this.sentSmsMapper = sentSmsMapper;
        this.yunPianSmsSenderAdapter = yunPianSmsSenderAdapter;
    }

    @Override
    BaseMapper<SentSms> getMapper() {
        return sentSmsMapper;
    }

    @Override
    public VerifySms sendVerifyCode(String number) {
        VerifySms res = doSendVerifyCode(number);
        if (res == null) {
            return null;
        }
        Date now = DateUtil.now();
        SentSms sentSms = new SentSms();
        sentSms.setCreateTime(now);
        sentSms.setMsg(res.getText());
        sentSms.setPhoneNumber(number);
        SentSms saveRes = save(sentSms);
        res.setSentSms(saveRes);
        return res;
    }

    /**
     * 执行发送短信验证码
     *
     * @param number 手机号码
     * @return 发送的验证码和发送的全部内容
     */
    private VerifySms doSendVerifyCode(String number) {
        try {
            return yunPianSmsSenderAdapter.sendVerificationCode(number);
        } catch (SmsSender.SendException e) {
            log.error("Verify code sms send error {}", e);
            return null;
        }
    }
}
